/**
 * Copyright (c) 2008, George Taylor
 * All rights reserved.
 * 
 * Redistribution and use in source and binary forms, with or without modification, are permitted 
 * provided that the following conditions are met:
 * 
 *   * Redistributions of source code must retain the above copyright notice, this list of 
 *     conditions and the following disclaimer.
 *   * Redistributions in binary form must reproduce the above copyright notice, this list of 
 *     conditions and the following disclaimer in the documentation and/or other materials 
 *     provided with the distribution.
 *   * Neither the name of the copyright holder's organization nor the names of its contributors 
 *     may be used to endorse or promote products derived from this software without specific 
 *     prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR 
 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND 
 * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR 
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL 
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER 
 * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT 
 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */
package uk.co.taylorconsulting.annoweb.web.builder;

import java.io.File;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.ArrayList;

import org.apache.log4j.Logger;

import uk.co.taylorconsulting.annoweb.web.controller.WebFramework;

import com.sun.tools.javac.Main;

public class Compiler {
	private static final Logger LOG = Logger.getLogger(Compiler.class);
	
	protected String removeDot(String clazzName) {
		while (clazzName.indexOf(".") > 0) {
			clazzName = clazzName.replace(".", "_");
		}
		return clazzName;
	}
	
	protected void makeDir(File tmp) {
		if (tmp.getParentFile() == null)
			return;
		while (!tmp.getParentFile().exists()) {
			makeDir(tmp.getParentFile());
		}
		if (!tmp.exists()) {
			tmp.mkdir();
		}
	}
	
	protected WebFramework compile(File path) {
		try {
			PrintWriter pw = new PrintWriter(new OutputStreamWriter(System.out));
			LOG.debug("Loading libraries");
			String[] p = getParams(path);
			LOG.debug("Compiling with parameters :" + toString(p));
			String[] p2 = new String[p.length + path.listFiles().length];
			System.arraycopy(p, 0, p2, 0, p.length);
			int i = p.length;
			for (File f : path.listFiles()) {
				p2[i++] = f.getAbsolutePath();
			}
			Main.compile(p2, pw);
			Class<?> c = Class.forName("TCSiteController");
			return (WebFramework) c.newInstance();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (SecurityException e) {
			e.printStackTrace();
		} catch (InstantiationException e) {
			e.printStackTrace();
		}
		return null;
	}
	
	private String toString(String[] p) {
		StringBuffer str = new StringBuffer();
		boolean first = true;
		for (String s : p) {
			if (first) {
				first = false;
			} else {
				str.append(",");
			}
			str.append(s);
		}
		return str.toString();
	}
	
	private String[] getParams(File path) {
		ArrayList<String> params = new ArrayList<String>();
		params.add("-cp");
		StringBuffer cp = new StringBuffer(".").append(System.getProperty("path.separator")).append(path.getParentFile().getAbsolutePath()).append(File.separator).append("WEB-INF").append(File.separator).append("classes");
		addParentLibs(path, cp);
		addWebLibs(path, cp);
		addServerLibs(path, cp);
		params.add(cp.toString());
		params.add("-d");
		params.add(path.getParentFile().getAbsolutePath() + File.separator + "WEB-INF" + File.separator + "classes");
		String[] p = new String[params.size()];
		params.toArray(p);
		return p;
	}
	
	private void addServerLibs(File path, StringBuffer cp) {
		path = path.getParentFile();
		while (path != null && path.exists()) {
			File lib = null;
			File common = null;
			File serverLib = null;
			try {
				lib = new File(path, "lib");
			} catch (Exception e) {
				lib = null;
			}
			try {
				common = new File(path, "common");
			} catch (Exception e) {
				common = null;
			}
			try {
				serverLib = new File(path, "server");
				serverLib = new File(serverLib, "lib");
			} catch (Exception e) {
				serverLib = null;
			}
			if (lib != null && lib.exists()) {
				addLibs(lib, cp);
			}
			if (common != null && common.exists()) {
				addLibs(new File(common, "endorsed"), cp);
				addLibs(new File(common, "i18n"), cp);
				addLibs(new File(common, "lib"), cp);
			}
			path = path.getParentFile();
		}
	}
	
	private void addLibs(File dir, StringBuffer cp) {
		if (dir.exists()) {
			for (File child : dir.listFiles()) {
				addJarToClasspath(cp, child);
			}
		}
	}
	
	private void addWebLibs(File path, StringBuffer cp) {
		File lib = new File(new File(path.getParentFile(), "WEB-INF"), "lib");
		if (lib.exists()) {
			for (File child : lib.listFiles()) {
				addJarToClasspath(cp, child);
			}
		}
	}
	
	private void addParentLibs(File path, StringBuffer cp) {
		File lib = new File(path.getParentFile(), "lib");
		if (lib.exists()) {
			for (File child : lib.listFiles()) {
				addJarToClasspath(cp, child);
			}
		}
	}
	
	private void addJarToClasspath(StringBuffer cp, File child) {
		if (child.getName().endsWith(".jar")) {
			cp.append(System.getProperty("path.separator"));
			cp.append(child.getAbsolutePath());
		}
	}
}
